package com.boyu.common.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MailUtils
{
	public static void send(String to_address, String subject, String content)
	{
		MailThread m = new MailThread(to_address,subject,content);
		m.start();
	}
}

class MailThread  extends Thread
{
	private String to_address; 
	private String subject; 
	private String content;
	private static final String FROM = "";
	private static final String PASSWORD = "";
	public static final String ADMIN_EMAIL = "<font size='3' color='red'>本邮件为系统自动发送，请勿直接回复</font>";
	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	public MailThread(String to_address,String subject,String content)
	{
		this.to_address = to_address;
		this.subject = subject;
		this.content = content;
	}

	@Override
	public void run()
	{
		if(to_address==null || to_address.equals(""))
		{
			logger.info("发送邮件地址为空，发送失败");
			return;
		}
		try
		{
			// 配置发送邮件的环境属性
			logger.info("发送邮件开始");
			final Properties props = new Properties();
			props.put("mail.user", FROM);
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.host", "smtp.qq.com");
			props.put("mail.smtp.port", "465");
			props.put("mail.password", PASSWORD);
			props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			props.setProperty("mail.smtp.socketFactory.fallback", "false");
			props.setProperty("mail.smtp.socketFactory.port", "465");
			// 构建授权信息，用于进行SMTP进行身份验证
			Authenticator authenticator = new Authenticator()
			{
				@Override
				protected PasswordAuthentication getPasswordAuthentication()
				{
					// 用户名、密码
					String userName = props.getProperty("mail.user");
					String password = props.getProperty("mail.password");
					return new PasswordAuthentication(userName, password);
				}
			};
			// 使用环境属性和授权信息，创建邮件会话
			Session mailSession = Session.getInstance(props, authenticator);
			// 创建邮件消息
			MimeMessage message = new MimeMessage(mailSession);
			// 设置发件人
			InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
			message.setFrom(form);

			// 设置多个收件人
			InternetAddress[] internetAddressTo =InternetAddress.parse(to_address);
			message.setRecipients(Message.RecipientType.TO, internetAddressTo);

			// 设置邮件标题
			message.setSubject(subject);

			// 设置邮件的内容体
			content = content + "<br><br><br>" + ADMIN_EMAIL;
			message.setContent(content, "text/html;charset=UTF-8");

			// 发送邮件
			Transport.send(message);
			logger.info("发送邮件结束");
		}
		catch (Exception e)
		{
			logger.error("发送邮件失败 [to_address]=" + to_address + " [subject]=" + subject + " e=" + e);
			e.printStackTrace();
		}
	}
}